using System;
using System.ServiceModel;
using System.Threading;

namespace RemoteWorker.Worker
{
    public class ServerConnectionManager
    {
        public ServerConnectionManager(Worker worker)
        {
            _worker = worker;
        }

        public void Connect()
        {
            _pingThread = new Thread(ConnectionThreadWorker);
            _pingThread.Start();
        }

        public void Disconnect()
        {
            _pingThread.Abort();

            if (_workerServerConnection.State == CommunicationState.Opened)
                _workerServerConnection.Disconnect(_worker.Name);
        }

        public WorkerServerConnection WorkerServerConnection
        {
            get { return _workerServerConnection; }
        }

        private void ConnectionThreadWorker()
        {
            _workerServerConnection = new WorkerServerConnection(_worker); _workerServerConnection = new WorkerServerConnection(_worker);
            while (true)
            {
                try
                {
                    if (_workerServerConnection.State != CommunicationState.Opened)
                        _Connect();
                    else
                        _workerServerConnection.Ping(_worker.Name);

                    Thread.Sleep(30000);
                }catch
                {
                    Thread.Sleep(60000);
                }
            }
        }

        private void _Connect()
        {
            int tryCount = 0;
            while (_workerServerConnection.State != CommunicationState.Opened)
            {
                try
                {
                    tryCount++;
                    _workerServerConnection = new WorkerServerConnection(_worker);
                    _workerServerConnection.Ping(_worker.Name);
                }
                catch (Exception)
                {
                    if (tryCount%100 == 0)
                        Thread.Sleep(1000);
                    else
                        Thread.Sleep(5000);
                }
            }
        }

        private Thread _pingThread;
        private Worker _worker;
        private WorkerServerConnection _workerServerConnection;
    }
}